package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;

public class CnfolNewsAnalyse implements AnalyseNews {

	//http://news.cnfol.com/zhengquanyaowen/20140121/16816463.shtml
	//http://sc.stock.cnfol.com/shichangceping/20140121/16815436.shtml
	private static final String[] regex={
		"http://.*cnfol.com/[0-9]*/[0-9,]+.shtml",
		"http://.*.cnfol.com/[a-z]*/[0-9]{8}/[0-9]*.shtml",
		"http://.*.cnfol.com/.*/[0-9]{8}/[0-9]*_[0-9]*.shtml",
		"http://[0-9a-z]+.cnfol.com/[a-z0-9\\/]+.shtml"
	};

	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		String url=urlMeta.getUrl();

		String htmltxt=urlMeta.getHtml();
		Document doc=Jsoup.parse(htmltxt);
		String title=null;
		String content=null;
		Long date=null;

		NewsMeta news=new NewsMeta();

		String author=null;

		if (StringUtils.isBlank(title)) {
			title=doc.select("h1").text();
		}
		if (StringUtils.isBlank(title)) {
			title=doc.select("div#title").text();
		}
		if (StringUtils.isBlank(title)) {
			title=doc.select("div.wzy2L1").text();
		}
		if (StringUtils.isBlank(title)) {
			title=doc.select("div.title").text();
		}
		doc.select(".share_btn,#sendBbs,#sendQq").remove();
		content=JSoupUtils.selectContent(url,doc, "#Content","#__content");

		date  =DateUtils.matchDate(doc.select("span#pubtime_baidu").text());
		if(date ==null ){
			date=DateUtils.matchDate(doc.select("div.Tsb").text());
		}
		if(date ==null ){
			date=DateUtils.matchDate(url);
		}


		author=JSoupUtils.matchAuthor(doc, "来源：");
		news.setAuthor(author);


		news.setUrl(url);
		news.setTitle(title);
		news.setContent(content);
		news.setDate(date);
		return news;
	}

	public static void main(String[] args) {
		String url="http://xianhuo.cnfol.com/huagongfangzhi/20140814/18678415.shtml";
		CnfolNewsAnalyse test=new CnfolNewsAnalyse();
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(test.isDetailPage(url));
		System.out.println(url);
		System.out.println(DoMainUtils.GetDomainName(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		NewsMeta parserHtml=test.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
